<script setup lang="ts">
import { ref, onMounted } from "vue";
import {Delete, Edit, InfoFilled} from "@element-plus/icons-vue";
import {queryForwarder, saveForwarder, getForwarderById, requpdateEmp, reqdeleteForwarder} from "@/api/forwarder.js";
import router from "@/router";
import {ElMessage} from "element-plus";
import { checkUser } from "@/api/sysuser.js";
const tableData = ref([]);

//分页信息
const page = ref(1); //当前页 默认第1页
const pageSize = ref(10); //每页记录数
const total = ref(0); //总记录数
//每页记录数变化
function chgsize(size) {
  //更改每页记录数
  pageSize.value = size;
  //从每页开始查询
  page.value = 1;
  //查询数据
  initData();
}
//页面发生变化
function chgpg(pg) {
  //更改当前页
  page.value = pg;
  //查询数据
  initData();
}
//修改
async function update(row) {
  const id = row.id;

  let r = await getForwarderById(id);
  if (r.code == 200){
    form.value = r.data;
    console.log("r.data>>>", r.data)
    // 保存原始账号和密码
    eee.value.originalAccount = r.data.account;
    eee.value.originalPassword = r.data.password;
    isEdit.value = true;
    add.value = true;
  }else {
    ElMessage({
      message: "查询失败",
    });
  }
}
let eee = ref({
  originalAccount: "",
  originalPassword: "",
})
// 重新加载修改框的数据
function loadOriginalData() {
  // 假设您有一个函数可以重新获取原始数据
  // 这里我们直接使用eee.value来模拟
  form.value.account = eee.value.originalAccount;
  form.value.password = eee.value.originalPassword;
}
async function update2(){
  // 获取原始的账号和密码
  const originalAccount = eee.value.originalAccount; // 假设您在获取货代信息时保存了原始账号
  const originalPassword = eee.value.originalPassword; // 假设您在获取货代信息时保存了原始密码

  // 检查账号和密码是否被修改
  if (form.value.account !== originalAccount || form.value.password !== originalPassword) {
    ElMessage.error("账号或密码被修改，请重新输入");
    // 重新加载修改框的数据
    loadOriginalData();
    return; // 如果账号或密码被修改，则阻止进一步操作
  }
  //将修改的数据发送给后台，发生请求
  let rs = await requpdateEmp(form.value)
  //修改成功后 提示修改成功，再查找所有的数据
  if (rs.code == 200) {
    ElMessage.success(rs.msg);
  }
  resetForm();
  await initData();
  add.value = false;

}
//搜索条件
const filters = ref({
  companyName: "",
  contactPhone: "",
  email: ""
});
//重置
function reset() {
  filters.value= {
    companyName: "",
    contactPhone: "",
    email: ""
  };
  initData();
}
// 获取货代列表
async function initData() {
  let data = {
    page: page.value,
    pageSize: pageSize.value,
    companyName: filters.value.companyName,
    contactPhone: filters.value.contactPhone,
    email: filters.value.email
  };
  //请求
  let res = await queryForwarder(data);
  console.log("res>>>", res)
  if(res.code == 200){
    tableData.value = res.data.data;
    //接收分页信息
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
    total.value = res.data.total;
  }else {
    ElMessage({
      message: "查询失败",
      type: "error"
    });
  }

}
function resetForm() {
  form.value = {
    companyName: "",
    contactPerson: "",
    contactPhone: "",
    email: "",
    transportationMethod: "",
    preferredRoutes: "",
    account: "",
    password: "",
  };
}
let add = ref(false);
let isEdit = ref(false);
let form = ref({
  companyName: "",
  contactPerson: "",
  contactPhone: "",
  email: "",
  transportationMethod: "",
  preferredRoutes: "",
  account: "",
  password: "",
});
async function Addemp() {
  isEdit.value = false;
  if (form.value.account == "") {
    ElMessage({
      message: "请输入账号",
      type: "warning"
    });
    return; //程序 返回  不再执行
  }
  if (form.value.password == "") {
    ElMessage({
      message: "请输入密码",
      type: "warning"
    });
    return; //程序 返回  不再执行
  }
  const valid = await formRef.value.validate();
  if (!valid) {
    return;
  }
  //将新增的数据添加到数据库，发生请求
  let res = await saveForwarder(form.value);
  if (res.code === 0) {

  } else if (res.code !== 200) {
    ElMessage({
      message: "检查账号时发生错误",
      type: "error",
    });
  }
  //添加成功后 提示添加成功，再查找所有的数据
  if (res.code == 200) {
    ElMessage({
      message: "添加成功",
      type: "success"
    });
    resetForm();
    await initData();
    add.value = false;

  }
}


//声明周期狗子
onMounted(()=> {
  initData();
})
//运输方式
const method = [
  {
    label: "中国-北美",
    value: 1
  },
  {
    label: "中国-美加",
    value: 2
  },
  {
    label: "中国-欧洲",
    value: 3
  },
  {
    label: "中国-澳大利亚/新西兰",
    value: 4
  },
  {
    label: "中国-中南美",
    value: 5
  },
  {
    label: "中国-红海/地中海",
    value: 6
  },
  {
    label: "中国-日本/韩国/俄罗斯",
    value: 7
  },
  {
    label: "中国-东南亚",
    value: 8
  },
  {
    label: "中国-中东/波斯湾",
    value: 9
  },
  {
    label: "中国-中东/印巴",
    value: 10
  },
  {
    label: "中国-黑海/亚德里海湾",
    value: 11
  },
  {
    label: "中国-南美东/南美西",
    value: 12
  },
  {
    label: "中国-欧洲内陆",
    value: 13
  },
  {
    label: "中国-东非",
    value: 14
  },
  {
    label: "中国-西非",
    value: 15
  },
  {
    label: "中国-南非",
    value: 16
  },
  {
    label: "中国-北非",
    value: 17
  },
  {
    label: "中国-加勒比海",
    value: 18
  },
  {
    label: "中国-大马士革",
    value: 19
  },
  {
    label: "中国-科隆",
    value: 20
  },
  {
    label: "中国-菲律宾",
    value: 21
  },
  {
    label: "中国-香港/澳门",
    value: 22
  }
];
//擅长航线
const airline = [
  {
    label: "内销",
    value: 1
  },
  {
    label: "外销",
    value: 2
  }
];

// 表单校验规则
const rules = {
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 6, max: 12, message: "账号长度必须为6-12个字符", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 12, message: "密码长度必须为6-12个字符", trigger: "blur" }
  ]
};
const formRef = ref(null);
//取消删除对话框
function cancelEvent() {
  ElMessage({
    message: "取消删除成功",
    type: "success"
  });
}

/**
 * 根据id删除数据
 * @param row
 */
/*function deleteForwarder(row) {
  console.log("删除的行", row)
  const id = row.id;
  let res =  reqdeleteForwarder(id);
  if (res.code == 200) {
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    initData();
  }
}*/
function deleteForwarder(row) {
  const id = row.id;
  reqdeleteForwarder(id).then(response => {
    if (response.code == 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      initData(); // 刷新数据
    } else {
      ElMessage({
        message: "删除失败：" + response.msg,
        type: "error"
      });
    }
  }).catch(error => {
    console.error("删除失败：", error);
    ElMessage.error("删除失败");
  });
}
//检测账号是否存在
async function chk() {
  if (form.value.account == "") {
    ElMessage({
      message: "请输入账号",
      type: "warning"
    });
    return; //程序 返回  不再执行
  }
  //验证账号是否存在
  let res = await checkUser(form.value.account);
  if (res.code == 200) {
    if (res.data == "yes") {
      ElMessage({
        message: "该账号已存在！",
        type: "warning"
      });
    }
  }
}
</script>

<template>
  <div>

    <el-dialog
      v-model="add"
      :title="isEdit? '修改货代信息' : '新增货代信息'"
      width="500"
      @close="resetForm"
    >
      <el-form :model="form"  :rules="rules" ref="formRef">
        <el-form-item label="账号:" prop="account">
          <el-input v-model="form.account" placeholder="请输入" @blur="chk"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入" ></el-input>
        </el-form-item>
        <el-form-item label="货代公司名称:" >
          <el-input v-model="form.companyName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="联系人:">
          <el-input v-model="form.contactPerson" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="联系电话:">
          <el-input  v-model="form.contactPhone" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="邮箱:">
          <el-input v-model="form.email" placeholder="请输入"></el-input>
        </el-form-item>
<!--        <el-form-item label="运输方式:">
          <el-input v-model="form.transportationMethod" placeholder="请输入"></el-input>
        </el-form-item>-->
        <el-form-item label="运输方式:" >
          <el-select v-model="form.transportationMethod" placeholder="请选择">
            <el-option v-for="item in method" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

<!--        <el-form-item label="擅长航线:">
          <el-input v-model="form.preferredRoutes" placeholder="请输入"></el-input>
        </el-form-item>-->
        <el-form-item label="擅长航线" >
          <el-select v-model="form.preferredRoutes" placeholder="请选择 内销、外销">
            <el-option v-for="item in airline" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="add = false;resetForm()">取消</el-button>
          <el-button type="primary" @click="isEdit ?  update2():Addemp()">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--客户搜索-->
    <div>
      <el-form>
        <el-row>
          <el-col :span="6">
            <el-form-item label="货代公司名称:"  style="margin-right: 5px;">
              <el-input v-model="filters.companyName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="联系方式:" style="margin-right: 5px;">
              <el-input v-model="filters.contactPhone" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
          <el-form-item label="邮箱:" style="margin-right: 15px;">
            <el-input v-model="filters.email" placeholder="请输入" />
          </el-form-item>
        </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="initData">搜索</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
          </el-col>
        </el-row>

      </el-form>
    </div>
    <!--功能按钮-->
    <div style="text-align: left">
      <el-button type="primary" @click="add=true,isEdit=false">添加</el-button>
    </div>
<!--    货代列表-->
    <el-table :data="tableData" style="width: 100%" stripe border>
      <el-table-column
        type="index"
        label="行号"
        width="80"
        header-align="center"
        align="center"
      />
      <el-table-column prop="id" label="ID" width="100"  header-align="center" align="center"/>
      <el-table-column prop="companyName" label="货代公司名称" width="200"  header-align="center" align="center"/>
      <el-table-column prop="contactPerson" label="联系人" width="120"  header-align="center" align="center"/>
      <el-table-column prop="contactPhone" label="联系方式" width="120"  header-align="center" align="center"/>
      <el-table-column prop="email" label="邮箱" width="200"  header-align="center" align="center"/>
      <el-table-column prop="createdAt" label="创建时间" width="180"  header-align="center" align="center"/>
      <el-table-column label="操作"  header-align="center"  align="center">
        <template #default="scope">
          <el-button
            type="primary"
            :icon="Edit"
            circle
            title="修改"
            @click="update(scope.row)"
          />
          <el-popconfirm
            confirm-button-text="Yes"
            cancel-button-text="No"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="你确定要删除此条数据?"
            @confirm="deleteForwarder(scope.row)"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button link type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>
    <!--分页-->
    <div
      style="
        background-color: #fff;
        height: 50px;
        line-height: 50px;
        text-align: right;
      "
    >
      <el-pagination
        background
        :page-size="pageSize"
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
        @size-change="chgsize"
        @current-change="chgpg"
      />
    </div>
  </div>

</template>

<style scoped>

</style>
